package top.codedance.iotp.tools.terminal.ui;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import top.codedance.iotp.common.constent.Command;
import top.codedance.iotp.common.util.JsonUtil;
import top.codedance.iotp.tools.terminal.TerminalApplication;

import javax.swing.*;
import java.awt.*;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 *
 * @author xuedianfu
 */
public class AddPluginParams extends javax.swing.JDialog {

    private ClientPluginTester cpt;
    private int rowIndex = -1;

    /**
     * Creates new form AddPluginParams
     */
    public AddPluginParams(ClientPluginTester cpt, JSONObject initData) {
        super(cpt, true);
        this.cpt = cpt;
        initComponents();
        URL url = Thread.currentThread().getContextClassLoader().getResource("logo.gif");
        ImageIcon icon = new ImageIcon(url);
        setIconImage(icon.getImage());
        setDefaultCloseOperation(DISPOSE_ON_CLOSE);
        setLocationRelativeTo(this.cpt.getShellFrame());
        setMinimumSize(new Dimension(400, 200));
        setTitle("代码飞舞采控系统-管理客户端插件参数");

        initEditData(initData);
    }

    private void initEditData(JSONObject initData){
        if(initData != null){
            JSONObject client = initData.getJSONObject("client");
            jta_params.setText(client.toJSONString());
            rowIndex = initData.getIntValue("rowIndex");
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jta_params = new javax.swing.JTextArea();
        jLabel1 = new javax.swing.JLabel();
        jb_add = new javax.swing.JButton();
        jb_format = new javax.swing.JButton();
        jb_get = new javax.swing.JButton();
        jb_copy = new javax.swing.JButton();
        jb_clean = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jta_params.setColumns(20);
        jta_params.setFont(new java.awt.Font("Microsoft YaHei UI", 0, 14)); // NOI18N
        jta_params.setRows(5);
        jScrollPane1.setViewportView(jta_params);

        jLabel1.setText("配置参数：");

        jb_add.setText("保存为设置命令");
        jb_add.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jb_addActionPerformed(evt);
            }
        });

        jb_format.setText("格式化JSON数据");
        jb_format.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jb_formatActionPerformed(evt);
            }
        });

        jb_get.setText("保存为获取命令");
        jb_get.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jb_getActionPerformed(evt);
            }
        });

        jb_copy.setText("复制控制台数据到当前");
        jb_copy.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jb_copyActionPerformed(evt);
            }
        });

        jb_clean.setText("清空");
        jb_clean.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jb_cleanActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 765, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel1)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jb_add)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(jb_get)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(jb_format)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jb_copy)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jb_clean)))
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addGap(4, 4, 4)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 402, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 10, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jb_add)
                    .addComponent(jb_format)
                    .addComponent(jb_get)
                    .addComponent(jb_copy)
                    .addComponent(jb_clean))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private String getTime(){
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
        return sdf.format(new Date());
    }

    private void jb_addActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jb_addActionPerformed
        int isYes = JOptionPane.YES_OPTION;
        if(jta_params.getText().isEmpty()) {
            isYes = JOptionPane.showConfirmDialog(this, "没有找到数据，确认要设置为空配置吗？", "确认窗口", JOptionPane.YES_NO_OPTION);
        }
        if(isYes == JOptionPane.YES_OPTION) {
            try {
                JSONObject commandParams = new JSONObject();
                commandParams.put("plugin", Command.CLIENT_PLUGINS_PARAMS_SET);
                JSONObject clientJo = JSON.parseObject(jta_params.getText());
                commandParams.put("client", clientJo);
                if(rowIndex < 0) {
                    String defaultName = "SetPluginParams-" + getTime();
                    String name = (String) JOptionPane.showInputDialog(this, "如需重新起名，请输入新的名称。", "保存命令", JOptionPane.QUESTION_MESSAGE, null, null, defaultName);
                    if (name == null || name.isEmpty()) {
                        name = defaultName;
                    }
                    cpt.addPluginParam(commandParams, name);
                }else{
                    cpt.addPluginParam(commandParams, rowIndex);
                }
                setVisible(false);
            } catch (Exception e) {
                TerminalApplication.syslogInfo(e.getMessage());
                JOptionPane.showMessageDialog(rootPane, "数据不能格式化为JSON对象，请检查后重试。");
            }
        }
    }//GEN-LAST:event_jb_addActionPerformed

    private void jb_getActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jb_getActionPerformed
        JSONObject commandParams = new JSONObject();
        commandParams.put("plugin", Command.CLIENT_PLUGINS_PARAMS_GET);
        JSONObject clientJo = new JSONObject();
        commandParams.put("client", clientJo);
        String defaultName = "GetPluginParams-" + getTime();
        String name = (String)JOptionPane.showInputDialog(this, "如需重新起名，请输入新的名称。", "保存命令", JOptionPane.QUESTION_MESSAGE, null, null, defaultName);
        if(name == null || name.isEmpty()){
            name = defaultName;
        }
        cpt.addPluginParam(commandParams, name);
        setVisible(false);
    }//GEN-LAST:event_jb_getActionPerformed

    private void jb_formatActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jb_formatActionPerformed
        jta_params.setText(JsonUtil.getInstance().format(jta_params.getText()));
    }//GEN-LAST:event_jb_formatActionPerformed

    private void jb_copyActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jb_copyActionPerformed
        jta_params.setText(cpt.getConsoleData());
    }//GEN-LAST:event_jb_copyActionPerformed

    private void jb_cleanActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jb_cleanActionPerformed
        jta_params.setText("");
    }//GEN-LAST:event_jb_cleanActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel jLabel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JButton jb_add;
    private javax.swing.JButton jb_clean;
    private javax.swing.JButton jb_copy;
    private javax.swing.JButton jb_format;
    private javax.swing.JButton jb_get;
    private javax.swing.JTextArea jta_params;
    // End of variables declaration//GEN-END:variables
}
